package cn.wen.base.decoration;

import android.content.Context;
import android.graphics.Rect;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;

/**
 * 使用GridLayoutManager的间距
 */

public class GridItemDistanceDecoration extends RecyclerView.ItemDecoration {
    private float mInstance;
    private Context mContext;

    public GridItemDistanceDecoration(Context context, float instance) {
        this.mContext = context;
        this.mInstance = dip2px(instance);
    }

    private float dip2px(float dip) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, mContext.getResources().getDisplayMetrics());
    }

    public GridItemDistanceDecoration(Context context) {
        this(context, 10f);
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        // 留出空间来画分割线
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        int right = (int) mInstance;
        if (layoutManager instanceof GridLayoutManager) {
            GridLayoutManager manager = (GridLayoutManager) layoutManager;
            int spanCount = manager.getSpanCount();
            int position = parent.getChildLayoutPosition(view);
            if ((position + 1) % spanCount == 0) {
                right = 0;
            }
        }
        outRect.right = right;


    }


}
